package com.example.hello.controller;

import com.example.hello.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "测试接口", description = "系统测试相关接口")
@RestController
@RequestMapping("/api/test")
public class TestController {

  @Autowired
  private JdbcTemplate jdbcTemplate;
  
  @Value("${spring.application.name}")
  private String applicationName;

  @Operation(summary = "测试数据库连接", description = "测试与数据库的连接是否正常")
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "连接成功"),
      @ApiResponse(responseCode = "500", description = "连接失败")
  })
  @GetMapping("/db")
  public Result<List<Map<String, Object>>> testDb() {
    List<Map<String, Object>> result = jdbcTemplate.queryForList("SELECT 1 as test");
    return Result.success(result);
  }
  
  @Operation(summary = "测试网络连通性", description = "测试前端与后端的网络连通性")
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "连接成功")
  })
  @GetMapping("/ping")
  public Result<Map<String, Object>> ping() {
    Map<String, Object> data = new HashMap<>();
    data.put("timestamp", new Date());
    data.put("status", "UP");
    data.put("message", "服务器连接正常");
    data.put("application", applicationName);
    
    // 获取服务器信息
    Runtime runtime = Runtime.getRuntime();
    data.put("jvm", Map.of(
        "availableProcessors", runtime.availableProcessors(),
        "freeMemory", runtime.freeMemory(),
        "maxMemory", runtime.maxMemory(),
        "totalMemory", runtime.totalMemory()
    ));
    
    return Result.success(data);
  }
}